package com.hna.iot.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hna.iot.base.BaseController;
import com.hna.iot.model.BfMenu;
import com.hna.iot.model.BfRole2menu;
import com.hna.iot.model.BfUser;
import com.hna.iot.service.IBfMenuService;
import com.hna.iot.service.IBfRole2menuService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色菜单表管理
 * @author zl
 *
 */
@Controller
public class RoleMenuController extends BaseController{
	
	private final static Logger log = LoggerFactory.getLogger(RoleMenuController.class);
	@Autowired
	private IBfMenuService menuService;
	@Autowired
	private IBfRole2menuService role2MenuService;
	
	@RequestMapping("/rolemenu/index")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("pages/rolemenu/editrolemenu");
		mav.addObject("roleId", request.getParameter("roleId"));
		return mav;
	}
	
	@RequestMapping(value = { "/rest/roleMenuList" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> roleMenuList(HttpServletRequest request,String roleId) {
		Map<String, Object> res = new HashMap<String, Object>();
		List<Map> rows = new ArrayList<Map>();
		try {
			BfUser userSession =(BfUser)request.getSession().getAttribute("userInfo");
		    String username = userSession.getUsername();
		    Map<String, Object> para = new HashMap<String, Object>();
		    para.put("pid", 0);
		    List<BfMenu> menuList = new ArrayList<BfMenu>();
		    if (username.equals("admin")) {
		    	menuList = menuService.selectAdminMenu(para);
		    }else{
				    para.put("userName", username);
				    menuList = menuService.selectByUserNameAndPid(para);
		    }
			
			for (int i = 0; i < menuList.size(); i++) {
			      Map<String, Object> item = new HashMap<String, Object>();
			      item.put("id", menuList.get(i).getId());
			      item.put("text", menuList.get(i).getMenuname());
			 
				Map<String, Object> chpara = new HashMap<String, Object>();
			      chpara.put("pid", menuList.get(i).getId());
			      List<BfMenu> treeListChildren = new ArrayList<BfMenu>();
			      if (username.equals("admin")) {
			    	  treeListChildren = menuService.selectAdminMenu(chpara);
			      }else{        
			        chpara.put("userName", username);
			        treeListChildren = menuService.selectByUserNameAndPid(chpara);
			      }
			      menuList.addAll(treeListChildren);
			}
			int total =menuList.size();

			Wrapper<BfRole2menu> wrapper2=new EntityWrapper<BfRole2menu>();
			wrapper2.eq("roleid", roleId);
//			Role2MenuExample roleMenuExample = new Role2MenuExample();
//			roleMenuExample.createCriteria().andRoleidEqualTo(Long.valueOf(roleId));
			List<BfRole2menu> roleMenuList = role2MenuService.selectList(wrapper2);

			for (BfMenu menu : menuList) {
				Map<String, Object> row = new HashMap<String, Object>();
				row.put("id", menu.getId());
				row.put("menudesc", menu.getMenudesc());
				row.put("menuname", menu.getMenuname());
				row.put("menucode", menu.getMenucode());
				row.put("_parentId", menu.getPid());
				boolean b = false;
				for (BfRole2menu rm : roleMenuList) {
					if (menu.getId().equals(rm.getMenuid())) {
						b = true;
						break;
					}
				}
					row.put("checked", b);
					rows.add(row);
			
			}

			res.put("total", total);
			res.put("rows", rows);
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		}
	}

	@RequestMapping(value = { "/rest/roleMenuEdit" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> roleMenuEdit(HttpServletRequest request) {
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			BfUser userSession =(BfUser)request.getSession().getAttribute("userInfo");
			String roleId = request.getParameter("roleId");

			String ids = request.getParameter("ids");
//			Role2MenuExample example = new Role2MenuExample();
//			example.createCriteria().andRoleidEqualTo(Long.valueOf(roleId));
//			role2MenuService.deleteByRoleId(roleId);
			
			Wrapper<BfRole2menu> wrapper=new EntityWrapper<BfRole2menu>();
			wrapper.eq("roleid", roleId);
			role2MenuService.delete(wrapper);
			
			if(StringUtils.isNotEmpty(ids)){
				String[] menuIds = ids.split(",");
				List<BfRole2menu> role2MenuList = new ArrayList<BfRole2menu>();
				for (String menuId : menuIds) {
					BfRole2menu role2Menu = new BfRole2menu();
					role2Menu.setMenuid(Long.valueOf(menuId));
					role2Menu.setRoleid(Long.valueOf(roleId));
					role2MenuList.add(role2Menu);
				}
				role2MenuService.insertBatch(role2MenuList);
			}
			
			this.saveUserlog(request, "角色菜单管理："+userSession.getUsername()+"修改角色菜单操作");
			
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		}
	}
}
